//
//  String+Format.swift
//  Utility
//
//  Created by yuhus on 2023/10/25.
//

import Foundation

public extension String {
  static func formatted(_ number: Int) -> String {
    switch number {
    case 0..<999: return String(number)
    case 1000...: return String(format: "%.1fK", (Double(number) / 1000.0))
    default:
      return ""
    }
  }
  
  /// 每个版本占用两位数
  /// - 1.2.4 返回 10204
  var versionCode: Int? {
    let versionCode = self.split(separator: ".")
      .compactMap { Int($0) }
      .map { String(format: "%02d", $0) }
      .joined()
    return Int(versionCode)
  }
  
  func prefixAndCountCN(_ maxLength: Int) -> (String, Int) {
    var total: Int = 0
    for (index, char) in self.enumerated() {
      let charCount = "\(char)".lengthOfBytes(using: .utf8) == 3 ? 2 : 1
      total += charCount
      if total == maxLength {
        let prefix = String(self.prefix(min(index + 1, self.count)))
        return (prefix, total)
      } else if total > maxLength {
        let prefix = String(self.prefix(min(index, self.count)))
        return (prefix, total - charCount)
      }
    }
    return (self, total)
  }
  
  /// 提取奇数位字符串
  func oddCharacters() -> String {
    self.enumerated().filter { index, _ in
      index % 2 == 0
    }.map { _, character in
      String(character)
    }.joined()
  }
  
  /// 提取奇数位字符串
  func evenCharacters() -> String {
    self.enumerated().filter { index, _ in
      index % 2 == 1
    }.map { _, character in
      String(character)
    }.joined()
  }
}
